﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//using Newtonsoft.Json;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Data.SqlClient;
using System.Security.Cryptography;

namespace secureFTP_Client
{
    public partial class Form2 : Form
    {
        private Socket SendCommandSocket;
        private Socket DataTransportSocket;
        private ClientConfig clientConfig;
        private FTPUser user;
        public Form2(object CommandSocket, object dataSocket, object FTPuser, object config)
        {
            InitializeComponent();
            SendCommandSocket = CommandSocket as Socket;
            DataTransportSocket = dataSocket as Socket;
            clientConfig = config as ClientConfig;
            user = FTPuser as FTPUser;
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            /*
             * 列出本地目录的部分，此部分可以放在Form_Load过程中
             */
            listView2.Items.Clear();
            DirectoryInfo ClientCorrentDirectoryInfo = new DirectoryInfo(clientConfig.GetClientCorrentDirectory());
            if(ClientCorrentDirectoryInfo.Parent.FullName != null)
            {
                ListViewItem item = new ListViewItem();
                item.Text = "..";
                item.ImageIndex = 0;
                item.SubItems.Add("Directory");
                item.SubItems.Add("-");
                item.SubItems.Add(ClientCorrentDirectoryInfo.Parent.FullName);
                listView2.Items.Add(item);
            }
            FileSystemInfo[] LocalDirectoryInfo = ClientCorrentDirectoryInfo.GetFileSystemInfos();
            foreach(FileSystemInfo fileSystemInfo in LocalDirectoryInfo)
            {
                ListViewItem item = new ListViewItem();
                item.Text = fileSystemInfo.Name;
                item.ImageIndex = fileSystemInfo is DirectoryInfo ? 0 : 2;
                item.SubItems.Add(fileSystemInfo is DirectoryInfo ? "Directory" : "File");
                item.SubItems.Add(fileSystemInfo.LastWriteTime.ToString());
                item.SubItems.Add(fileSystemInfo.FullName);
                listView2.Items.Add(item);
            }

            /*
             *  登录认证过程
             */
            FTPUser justUser = new FTPUser();
            justUser.User = user.User; //第一个登录请求包只传输用户名
            justUser.PasswordSHA256 = "";
            justUser.Salt = "";
            DataPocket LoginDataPocket = new DataPocket();
            LoginDataPocket.PocketType = 11; //11表明是登录请求包
            LoginDataPocket.Content = JsonSerializer.SerializeToUtf8Bytes(justUser);
            byte[] SendLoginBuffer = JsonSerializer.SerializeToUtf8Bytes(LoginDataPocket);
            SendCommandSocket.Send(SendLoginBuffer);

            byte[] LoginReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
            int authPocketLength = SendCommandSocket.Receive(LoginReceiveBuffer);
            ReadOnlySpan<byte> LoginReceiveBufferSpan = new ReadOnlySpan<byte>(LoginReceiveBuffer, 0, authPocketLength);
            DataPocket authDataPocket = JsonSerializer.Deserialize<DataPocket>(LoginReceiveBufferSpan);
            if(authDataPocket.PocketType == 12)
            {
                //继续发送密码加盐sha256认证
                ReadOnlySpan<byte> FTPUserSpan = new ReadOnlySpan<byte>(authDataPocket.Content);
                FTPUser authUser = JsonSerializer.Deserialize<FTPUser>(FTPUserSpan);
                byte[] PasswordSHA256 = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(user.PasswordSHA256));
                String PasswordSHA256Str = BitConverter.ToString(PasswordSHA256).Replace("-", "").ToLower();
                byte[] SaltPasswordSHA256 = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(PasswordSHA256Str + authUser.Salt));
                String SaltPasswordSHA256Str = BitConverter.ToString(SaltPasswordSHA256).Replace("-", "").ToLower();
                authUser.Salt = "";
                authUser.PasswordSHA256 = SaltPasswordSHA256Str;
                user.IsVIP = authUser.IsVIP;

                //构造认证返回包
                authDataPocket.PocketType = 11;
                authDataPocket.Content = JsonSerializer.SerializeToUtf8Bytes(authUser);
                byte[] authSendBuffer = JsonSerializer.SerializeToUtf8Bytes(authDataPocket);
                SendCommandSocket.Send(authSendBuffer);

                //接收登录状态返回包
                byte[] LoginAuthReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
                int authStatusPocketLength = SendCommandSocket.Receive(LoginAuthReceiveBuffer);
                ReadOnlySpan<byte> LoginAuthReceiveBufferSpan = new ReadOnlySpan<byte>(LoginAuthReceiveBuffer, 0, authStatusPocketLength);
                DataPocket authStatusDataPocket = JsonSerializer.Deserialize<DataPocket>(LoginAuthReceiveBufferSpan);

                if(authStatusDataPocket.PocketType == 13)
                {
                    //登陆成功，可以继续
                }
                else if(authStatusDataPocket.PocketType == 14)
                {
                    //密码错误
                    MessageBox.Show("用户名或密码错误，登录认证失败!", "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    SendCommandSocket.Close(); //认证失败直接关闭连接，防止DDOS攻击
                    DataTransportSocket.Close(); //认证失败直接关闭连接，防止DDOS攻击
                    //this.Form2_FormClosing(sender, (FormClosingEventArgs)e);
                    //Form1.pForm1.Show();
                    this.Close();
                    return;
                }

            }
            else if(authDataPocket.PocketType == 14)
            {
                //用户名不存在结束认证
                MessageBox.Show("用户名不存在，登录认证失败!", "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                SendCommandSocket.Close(); //认证失败直接关闭连接，防止DDOS攻击
                DataTransportSocket.Close(); //认证失败直接关闭连接，防止DDOS攻击
                //this.Form2_FormClosing(sender, (FormClosingEventArgs)e);
                //Form1.pForm1.Show();
                this.Close();
                return;
            }




            /*
             * 以下为远端目录列出部分 
             */
            label1.Text = "当前Server : " + SendCommandSocket.RemoteEndPoint.ToString();
            //构造第一个列出目录包
            DataPocket ListFilesPocket = new DataPocket();
            ListFilesPocket.PocketType = 21;
            ListFilesPocket.PocketDataLength = 0;
            ListFilesPocket.Content = Encoding.UTF8.GetBytes("~");

            //发送列出目录包
            try
            {
                //byte[] SendBuffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(ListFilesPocket));
                //SendCommandSocket.Send(SendBuffer);
                byte[] SendBuffer = JsonSerializer.SerializeToUtf8Bytes(ListFilesPocket);
                SendCommandSocket.Send(SendBuffer);
                
                byte[] ReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
                int PocketLength =  SendCommandSocket.Receive(ReceiveBuffer);
                //Console.WriteLine(ReceiveBuffer);
                //String ReceiveString = Encoding.UTF8.GetString(ReceiveBuffer, 0, PocketLength);
                //Console.WriteLine(ReceiveString);
                //DataPocket ReceivedDirectoryPocket = JsonConvert.DeserializeObject<DataPocket>(ReceiveString);
                ReadOnlySpan<byte> ReceiveBufferSpan = new ReadOnlySpan<byte>(ReceiveBuffer, 0, PocketLength);
                DataPocket ReceivedDirectoryPocket = JsonSerializer.Deserialize<DataPocket>(ReceiveBufferSpan);
                //Console.WriteLine(ReceivedDirectoryPocket.ToString());

                //设置服务器端FTP的根目录
                clientConfig.SetServerRootDirectory(Encoding.UTF8.GetString(ReceivedDirectoryPocket.Content));

                //回显远端服务器目录
                //for (int i=0; i < ReceivedDirectoryPocket.FileAndDirectoryCount; i++)
                //{
                //    listBox1.Items.Add(ReceivedDirectoryPocket.FileAndDirectoryList[i].FullName);
                //}

                for (int i = 0; i < ReceivedDirectoryPocket.FileAndDirectoryCount; i++)
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = ReceivedDirectoryPocket.FileAndDirectoryList[i].Name;
                    item.ImageIndex = ReceivedDirectoryPocket.FileAndDirectoryList[i].FileOrDirectoryType == 1 ? 0 : 2;
                    item.SubItems.Add(ReceivedDirectoryPocket.FileAndDirectoryList[i].FileOrDirectoryType == 1 ? "Directory" : "File");
                    item.SubItems.Add(ReceivedDirectoryPocket.FileAndDirectoryList[i].LastWriteTime.ToString());
                    item.SubItems.Add(ReceivedDirectoryPocket.FileAndDirectoryList[i].FullName);
                    listView1.Items.Add(item);
                }
            }
            catch
            {
                MessageBox.Show("列出远端FTP目录失败！", "连接服务器失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Form1.pForm1.Show();
                this.Close();
            }


        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
            //Form1.pForm1.Show();
            //Form1.pForm1.Visible = true;
        }
        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Process.GetCurrentProcess().Kill();
            //Form1.pForm1.Show();
            //Form1.pForm1.Visible = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count != 0)
            {
                //List<ListViewItem> SelectedItems = new List<ListViewItem>();
                DataPocket RequiredFilePocket = new DataPocket();
                RequiredFilePocket.PocketType = 31; //31表示是向服务器请求文件的包
                foreach(ListViewItem item in listView1.SelectedItems)
                {
                    if (item.SubItems[1].Text.Equals("Directory"))
                    {
                        MessageBox.Show("所选项含有文件夹，暂不支持传输文件夹！", "不支持传输文件夹", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    FileOrDirectory file = new FileOrDirectory();
                    file.FileOrDirectoryType = 0;
                    file.FullName = item.SubItems[3].Text;
                    file.Name = item.Text;
                    RequiredFilePocket.FileAndDirectoryList.Add(file);
                    RequiredFilePocket.FileAndDirectoryCount++;
                }
                byte[] SendBuffer = JsonSerializer.SerializeToUtf8Bytes(RequiredFilePocket);
                SendCommandSocket.Send(SendBuffer);

                //接受反馈包并开始下载文件元数据
                byte[] ReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
                int PocketLength = SendCommandSocket.Receive(ReceiveBuffer);
                ReadOnlySpan<byte> ReceiveBufferSpan = new ReadOnlySpan<byte>(ReceiveBuffer, 0, PocketLength);
                DataPocket MetaData = JsonSerializer.Deserialize<DataPocket>(ReceiveBufferSpan);
                TransportHelper transportHelper = new TransportHelper();
                transportHelper.DataTransportSocket = DataTransportSocket;
                transportHelper.MetaDataPocket = MetaData;
                transportHelper.DownloadDirectory = clientConfig.GetClientCorrentDirectory();

                //开启接收数据线程
                if (MetaData.PocketType == 32)
                {
                    Thread DownloadHandle = new Thread(DownloadFilesThread);
                    DownloadHandle.IsBackground = true;
                    DownloadHandle.Start(transportHelper);
                }

            }

        }

        private void ListView1Item_DoubleClick(object sender, EventArgs e)
        {
            DataPocket FileOrDirectoryRequiredPocket = new DataPocket();
            if (listView1.SelectedItems[0].SubItems[1].Text.Equals("Directory"))
            {
                //发送远程文件目录请求包
                FileOrDirectoryRequiredPocket.PocketType = 21;
                String Directory = listView1.SelectedItems[0].SubItems[3].Text;
                FileOrDirectoryRequiredPocket.Content = Encoding.UTF8.GetBytes(Directory);
                //Console.WriteLine(FileOrDirectoryRequiredPocket.ToString());
                byte[] SendBuffer = JsonSerializer.SerializeToUtf8Bytes(FileOrDirectoryRequiredPocket);
                SendCommandSocket.Send(SendBuffer);

                //接受返回的目录包
                byte[] ReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
                int PocketLength = SendCommandSocket.Receive(ReceiveBuffer);
                ReadOnlySpan<byte> ReceiveBufferSpan = new ReadOnlySpan<byte>(ReceiveBuffer, 0, PocketLength);
                DataPocket ReceivedDirectoryPocket = JsonSerializer.Deserialize<DataPocket>(ReceiveBufferSpan);

                //回显刷新listview1进入新目录中
                if (ReceivedDirectoryPocket.PocketType == 22)
                {
                    listView1.Items.Clear();
                    //先渲染出一个返回上层的item
                    if (!(Directory.Equals(clientConfig.GetServerRootDirectory()) || clientConfig.GetServerRootDirectory().Contains(Directory)))
                    {
                        ListViewItem FirstItem = new ListViewItem();
                        FirstItem.Text = "..";
                        FirstItem.ImageIndex = 0;
                        FirstItem.SubItems.Add("Directory");
                        FirstItem.SubItems.Add("-");
                        String ParentDirectory = Directory.Substring(0, Directory.LastIndexOf('\\'));
                        Console.WriteLine(ParentDirectory);
                        FirstItem.SubItems.Add(ParentDirectory);
                        listView1.Items.Add(FirstItem);
                    }


                    //渲染查询到的目录列表
                    for (int i = 0; i < ReceivedDirectoryPocket.FileAndDirectoryCount; i++)
                    {
                        ListViewItem item = new ListViewItem();
                        item.Text = ReceivedDirectoryPocket.FileAndDirectoryList[i].Name;
                        item.ImageIndex = ReceivedDirectoryPocket.FileAndDirectoryList[i].FileOrDirectoryType == 1 ? 0 : 2;
                        item.SubItems.Add(ReceivedDirectoryPocket.FileAndDirectoryList[i].FileOrDirectoryType == 1 ? "Directory" : "File");
                        item.SubItems.Add(ReceivedDirectoryPocket.FileAndDirectoryList[i].LastWriteTime.ToString());
                        item.SubItems.Add(ReceivedDirectoryPocket.FileAndDirectoryList[i].FullName);
                        listView1.Items.Add(item);

                    }
                    clientConfig.SetServerCorrentDirectory(Directory);
                }
                else
                {
                    MessageBox.Show("远程目录访问出错，请确认服务端配置正确！", "远程访问出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

            }
            else
            {
                //发送文件下载请求包
                DataPocket FileRequirePocket = new DataPocket();
                FileRequirePocket.PocketType = 31; //31说明是文件下载请求包
                FileRequirePocket.FileAndDirectoryCount = 1;
                FileOrDirectory file = new FileOrDirectory();
                file.FileOrDirectoryType = 0;
                file.FullName = listView1.SelectedItems[0].SubItems[3].Text;
                FileRequirePocket.FileAndDirectoryList.Add(file);

                byte[] SendBuffer = JsonSerializer.SerializeToUtf8Bytes(FileRequirePocket);
                SendCommandSocket.Send(SendBuffer);

                //接收反馈包并下载文件元数据
                byte[] ReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
                int PocketLength = SendCommandSocket.Receive(ReceiveBuffer);
                ReadOnlySpan<byte> ReceiveBufferSpan = new ReadOnlySpan<byte>(ReceiveBuffer, 0, PocketLength);
                DataPocket MetaData = JsonSerializer.Deserialize<DataPocket>(ReceiveBufferSpan);
                TransportHelper transportHelper = new TransportHelper();
                transportHelper.DataTransportSocket = DataTransportSocket;
                transportHelper.MetaDataPocket = MetaData;
                transportHelper.DownloadDirectory = clientConfig.GetClientCorrentDirectory();
                
                //开启接收数据线程
                if (MetaData.PocketType == 32)
                {
                    Thread DownloadHandle = new Thread(DownloadFilesThread);
                    DownloadHandle.IsBackground = true;
                    DownloadHandle.Start(transportHelper);
                }


            }
        }

        private void ListView2Item_DoubleClick(object sender, EventArgs e)
        {
            if (listView2.SelectedItems[0].SubItems[1].Text.Equals("Directory"))
            {
                clientConfig.SetClientCorrentDirectory(listView2.SelectedItems[0].SubItems[3].Text);
                FileSystemInfo[] LocalDirectoryInfo = new DirectoryInfo(listView2.SelectedItems[0].SubItems[3].Text).GetFileSystemInfos();
                listView2.Items.Clear();
                if (new DirectoryInfo(clientConfig.GetClientCorrentDirectory()).Parent != null)
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = "..";
                    item.ImageIndex = 0;
                    item.SubItems.Add("Directory");
                    item.SubItems.Add("-");
                    item.SubItems.Add(new DirectoryInfo(clientConfig.GetClientCorrentDirectory()).Parent.FullName);
                    listView2.Items.Add(item);
                }
                foreach (FileSystemInfo fileSystemInfo in LocalDirectoryInfo)
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = fileSystemInfo.Name;
                    item.ImageIndex = fileSystemInfo is DirectoryInfo ? 0 : 2;
                    item.SubItems.Add(fileSystemInfo is DirectoryInfo ? "Directory" : "File");
                    item.SubItems.Add(fileSystemInfo.LastWriteTime.ToString());
                    item.SubItems.Add(fileSystemInfo.FullName);
                    listView2.Items.Add(item);
                }
            }
            else
            {
                //向服务器发包请求上传文件
                DataPocket UploadMetaDataPocket = new DataPocket();
                UploadMetaDataPocket.PocketType = 41; //41表示上传文件请求及文件元数据
                byte[] uploadDirectory = Encoding.UTF8.GetBytes(clientConfig.GetServerCorrentDirectory());
                UploadMetaDataPocket.Content = uploadDirectory;
                FileOrDirectory uploadFile = new FileOrDirectory();
                FileInfo file = new FileInfo(listView2.SelectedItems[0].SubItems[3].Text);
                uploadFile.FileOrDirectoryType = 0;
                uploadFile.FullName = file.FullName;
                uploadFile.Name = file.Name;
                uploadFile.Length = file.Length;
                uploadFile.LastWriteTime = file.LastWriteTime;
                UploadMetaDataPocket.FileAndDirectoryList.Add(uploadFile);
                UploadMetaDataPocket.FileAndDirectoryCount++;
                byte[] SendBuffer = JsonSerializer.SerializeToUtf8Bytes(UploadMetaDataPocket);
                SendCommandSocket.Send(SendBuffer);

                //接受反馈包并开启新线程上传
                byte[] ReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
                int DataPocketLength =  SendCommandSocket.Receive(ReceiveBuffer);
                ReadOnlySpan<byte> ReceiveBufferSpan = new ReadOnlySpan<byte>(ReceiveBuffer, 0, DataPocketLength);
                DataPocket EnsurePocket = JsonSerializer.Deserialize<DataPocket>(ReceiveBufferSpan);
                TransportHelper transportHelper = new TransportHelper();
                transportHelper.DataTransportSocket = DataTransportSocket;
                transportHelper.MetaDataPocket = UploadMetaDataPocket;
                if (EnsurePocket.PocketType == 42)
                {
                    Thread DownloadHandle = new Thread(UploadFilesThread);
                    DownloadHandle.IsBackground = true;
                    DownloadHandle.Start(transportHelper);
                }
                //接受反馈包并放弃上传
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count != 0)
            {
                //List<ListViewItem> SelectedItems = new List<ListViewItem>();
                DataPocket UploadMetaDataPocket = new DataPocket();
                UploadMetaDataPocket.PocketType = 41; //41表示上传文件请求包
                byte[] uploadDirectory = Encoding.UTF8.GetBytes(clientConfig.GetServerCorrentDirectory());
                UploadMetaDataPocket.Content = uploadDirectory;
                foreach (ListViewItem item in listView2.SelectedItems)
                {
                    if (item.SubItems[1].Text.Equals("Directory"))
                    {
                        MessageBox.Show("所选项含有文件夹，暂不支持传输文件夹！", "不支持传输文件夹", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    FileOrDirectory uploadFile = new FileOrDirectory();
                    FileInfo file = new FileInfo(item.SubItems[3].Text);
                    uploadFile.FileOrDirectoryType = 0;
                    uploadFile.FullName = file.FullName;
                    uploadFile.Name = file.Name;
                    uploadFile.Length = file.Length;
                    uploadFile.LastWriteTime = file.LastWriteTime;
                    UploadMetaDataPocket.FileAndDirectoryList.Add(uploadFile);
                    UploadMetaDataPocket.FileAndDirectoryCount++;
                }
                byte[] SendBuffer = JsonSerializer.SerializeToUtf8Bytes(UploadMetaDataPocket);
                SendCommandSocket.Send(SendBuffer);

                //接受反馈包并开启新线程上传
                byte[] ReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
                int DataPocketLength = SendCommandSocket.Receive(ReceiveBuffer);
                ReadOnlySpan<byte> ReceiveBufferSpan = new ReadOnlySpan<byte>(ReceiveBuffer, 0, DataPocketLength);
                DataPocket EnsurePocket = JsonSerializer.Deserialize<DataPocket>(ReceiveBufferSpan);
                TransportHelper transportHelper = new TransportHelper();
                transportHelper.DataTransportSocket = DataTransportSocket;
                transportHelper.MetaDataPocket = UploadMetaDataPocket;
                if (EnsurePocket.PocketType == 42)
                {
                    Thread DownloadHandle = new Thread(UploadFilesThread);
                    DownloadHandle.IsBackground = true;
                    DownloadHandle.Start(transportHelper);
                }

                //接受反馈包并放弃上传

            }
        }

        private void DownloadFilesThread(object obj)
        {
            TransportHelper helper = obj as TransportHelper;
            Socket DataSocket = helper.DataTransportSocket;
            DataPocket MetaPocket = helper.MetaDataPocket;
            //label2.Visible = true;
            //label3.Visible = true;
            //panel1.Visible = true;
            progressBar1.Value = 0;
            progressBar1.Maximum = MetaPocket.FileAndDirectoryCount;
            for(int i=0; i<MetaPocket.FileAndDirectoryCount; i++)
            {
                FileStream DownloadFile = new FileStream(helper.DownloadDirectory + '/' + MetaPocket.FileAndDirectoryList[i].Name, FileMode.Create, FileAccess.Write);
                BinaryWriter FileBinaryWriter = new BinaryWriter(DownloadFile);
                progressBar2.Value = 0;
                progressBar2.Maximum = (int)((MetaPocket.FileAndDirectoryList[i].Length + 1023) / 1024);
                for (int length=0; length<(MetaPocket.FileAndDirectoryList[i].Length + 1023) / 1024; length++)
                {
                    byte[] ReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
                    int DataPocketLength =  DataSocket.Receive(ReceiveBuffer);
                    ReadOnlySpan<byte> ReceiveBufferSpan = new ReadOnlySpan<byte>(ReceiveBuffer, 0, DataPocketLength);
                    DataPocket DownloadData = JsonSerializer.Deserialize<DataPocket>(ReceiveBufferSpan);
                    FileBinaryWriter.Write(DownloadData.Content);

                    DataPocket EnsurePocket = new DataPocket();
                    EnsurePocket.PocketType = 34;
                    byte[] SendBuffer = JsonSerializer.SerializeToUtf8Bytes(EnsurePocket);
                    DataSocket.Send(SendBuffer);
                    progressBar2.Value++;
                }
                FileBinaryWriter.Close();
                DownloadFile.Close();
                progressBar1.Value++;
            }
            //label2.Visible = false;
            //label3.Visible = false;
            //panel1.Visible = false;
        }

        private void UploadFilesThread(object obj)
        {
            TransportHelper helper = obj as TransportHelper;
            Socket DataSocket = helper.DataTransportSocket;
            DataPocket MetaPocket = helper.MetaDataPocket;
            //label2.Visible = true;
            //label3.Visible = true;
            //panel1.Visible = true;
            progressBar1.Value = 0;
            progressBar1.Maximum = MetaPocket.FileAndDirectoryCount;
            for (int i=0; i<MetaPocket.FileAndDirectoryCount; i++)
            {
                FileStream UploadFile = new FileStream(MetaPocket.FileAndDirectoryList[i].FullName, FileMode.Open, FileAccess.Read);
                BinaryReader UploadBinaryReader = new BinaryReader(UploadFile);
                progressBar2.Value = 0;
                progressBar2.Maximum = (int)((MetaPocket.FileAndDirectoryList[i].Length + 1023) / 1024);
                for (int length=0; length<(MetaPocket.FileAndDirectoryList[i].Length + 1023) / 1024; length++)
                {
                    byte[] fileContent = UploadBinaryReader.ReadBytes(1024);
                    DataPocket FileContentPocket = new DataPocket();
                    FileContentPocket.Content = fileContent;
                    FileContentPocket.PocketType = 33; //33表示此包为文件内容包
                    long RemainLength = MetaPocket.FileAndDirectoryList[i].Length - length * 1024;
                    FileContentPocket.PocketLength = (int)(RemainLength > 1024 ? 1024 : RemainLength);
                    byte[] SendBuffer = JsonSerializer.SerializeToUtf8Bytes(FileContentPocket);
                    DataSocket.Send(SendBuffer);

                    //等待确认此包后再发送下一个包
                    byte[] ReceiveBuffer = new byte[clientConfig.GetPocketBufferLength()];
                    int ReceiveLength = DataSocket.Receive(ReceiveBuffer);
                    ReadOnlySpan<byte> ReceiveBufferSpan = new ReadOnlySpan<byte>(ReceiveBuffer, 0, ReceiveLength);
                    DataPocket EnsurePocket = JsonSerializer.Deserialize<DataPocket>(ReceiveBufferSpan);
                    if (EnsurePocket.PocketType == 34) //34为数据包的确认包
                    {
                        progressBar2.Value++;
                        continue;
                    }
                    else
                    {
                        Console.WriteLine("客户端上传数据传输出现问题，文件为：" + MetaPocket.FileAndDirectoryList[i].FullName + "。\n传输到第" + length.ToString() + "个文件内容包。");
                    }
                }
                UploadBinaryReader.Close();
                UploadFile.Close();
                progressBar1.Value++;
            }
            //label2.Visible = false;
            //label3.Visible = false;
            //panel1.Visible = false;
        }
    }
}
